package com.iwhalecloud.bss.kite.cucc.web.interceptor;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.dataservice.cache.DcSystemParamCache;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.pub.client.constanst.Symbols;
import com.ztesoft.bss.common.exception.BssException;
import com.ztesoft.bss.common.util.ContextUtil;
import com.ztesoft.common.logger.api.ZLogger;
import com.ztesoft.common.logger.factory.ZLoggerFactory;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * 该拦截器使用运营平台的sessionid作为保存登录信息的key，
 * 故需要com.ztesoft.bss.common.util.ContextUtil#setHttpSessoinId(java.lang.String)设置sessionid
 */
public class LocalSessionInterceptor extends AbstractSessionInterceptor {

    private static final ZLogger LOGGER = ZLoggerFactory.getLogger(LocalSessionInterceptor.class, KeyConsts.LOG_MODULE);

    @Override
    protected boolean handle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException, ServletException {
        // 运营平台sessionid
        String sessionId = request.getHeader("cd");
        String appId = request.getHeader("appId");
        String custId = Optional.ofNullable(request.getHeader("custId")).orElse("");
        String requestUrl = request.getRequestURI();
        if (KiteStringUtils.contains(requestUrl, "/initCollectGroupScene")) {
            // 收入归集场景初始化时未选择客户，使用虚拟客户进行初始化
            custId = DcSystemParamCache.getDcParamVal(LocalKeyConsts.COLLECTION_GROUP_CUST_ID);
        }
        // 调toMenu方法时是通过URL的authSessionId传sessionid
        if (StringUtils.isBlank(sessionId)) {
            sessionId = request.getParameter("authSessionId");
        }
        if (StringUtils.isBlank(sessionId)) {
            sessionId = getCookie(request, NAME_SESSION);
        }
        if (KiteStringUtils.isEmpty(sessionId)) {
            BssException.throwOut("41301002", "S-SYS-00027", "登录已超时，请重新登录");
        }
        // 这里必须设置sessionid
        ContextUtil.setHttpSessoinId(sessionId);
        // 设置上下文key
        KiteWebContext.setKiteContextId(KiteStringUtils.joinWith(Symbols.HASH, sessionId, custId));
        if (request.getRequestURI().contains("/cuccMenu/toMenu")) {
            handleMenu(request, response, sessionId);
            return true;
        }
        this.doLogin(sessionId, appId, request, response);
        return true;
    }

}
